package com.zhangyuji.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhangyuji.common.R;
import com.zhangyuji.common.SendMsgUtil;
import com.zhangyuji.dto.UserDto;
import com.zhangyuji.entity.User;
import com.zhangyuji.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 发送qq邮箱验证码
     *
     * @param user
     * @param session
     * @return
     */

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        log.info("手机号:{}", user.getPhone());
        String code = SendMsgUtil.generatRandom(4);
        log.info("code={}", code);
        SendMsgUtil.sendMsg("941608267@qq.com", code);
        session.setAttribute(user.getPhone(), code);
        return R.success("发送成功");
    }

    /**
     * 登录验证
     *
     * @param userDto
     * @param request
     * @return
     */
    @PostMapping("/login")
    public R<String> login(@RequestBody UserDto userDto, HttpServletRequest request) {
        log.info("userDto={}", userDto.toString());
        String code = (String) request.getSession().getAttribute(userDto.getPhone());
        log.info("code={}", code);
        if (code != null) {
            if (code.equals(userDto.getCode())) {
                request.getSession().setAttribute("user", userDto.getPhone());
                LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(User::getPhone, userDto.getPhone());
                User user = userService.getOne(queryWrapper);
                if (user == null) {
                    boolean flag = userService.save(userDto);
                    if (flag) {
                        return R.success("登陆成功");
                    }
                    return R.error("登陆失败");
                }
                return R.success("登陆成功");
            }
            return R.error("验证码不正确");
        }
        return R.error("验证码已过期,请重新发送");
    }


    @PostMapping("/loginout")
    public R<String> loginout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");

        return R.success("成功退出");

    }
}
